<?php
require_once "config.php";
global $CONFIG;
$fileName = "funcs_" . $CONFIG['vendor'] . ".php";


if (file_exists("./php/$fileName")) {
    require_once "./php/$fileName";

} elseif (file_exists('./$fileName')) {
    require_once "./$fileName";

} elseif (file_exists('../php/$fileName')) {
    require_once "../php/$fileName";
}

$memcachedClient = null;

//redis存session
class RedisSessionHandler implements SessionHandlerInterface
{

    private $redis;
    private $cfg;
    private $namespace;
    private $session_id = null;
    private $maxlifetime = null;

    public function __construct($namespace, $host, $port)
    {
        //初始化redis
        $this->cfg = array(
            'host' => $host,
            'port' => $port
        );
        $this->redis = new Redis();
        $this->redis->connect($this->cfg['host'], $this->cfg['port']);
        //设置当前的sessionid生成的命名空间
        $this->namespace = $namespace;
        //设置初始化的session_id
        $session_name = ini_get("session.name");
        //没有设置过session，新的会话，需要重新生成sessionid
        if (empty($_COOKIE[$session_name])) {
            $this->session_id = true;
        }
    }

    public function open($savePath, $sessionName)
    {
        $connect = $this->redis->connect($this->cfg['host'], $this->cfg['port']);
        if (!$connect) return false;
        //在初次设置的时候，重设PHP本身的session_id并判断session_id是否已经存在
        $id = session_id();
        if ($this->session_id && $this->session_id != $id) {
            do {
                $this->session_id = $this->session_id();
            } while ($this->redis->exists($this->namespace . $this->session_id));
            session_id($this->session_id);
        }
        //设置生成周期
        //$this->maxlifetime = ini_get("session.gc_maxlifetime");
        $this->maxlifetime = 2592000;
        return true;
    }

    public function close()
    {
        $this->redis->close();
        return true;
    }

    public function read($id)
    {
        return $this->redis->get($this->namespace . $id);
    }

    public function write($id, $data)
    {
        return $this->redis->setex($this->namespace . $id, $this->maxlifetime, $data);
    }

    public function destroy($id)
    {
        $this->redis->delete($this->namespace . $id);
        return true;
    }

    public function gc($maxlifetime)
    {
        return true;
    }

    /**
     * 生成guid
     */
    private function session_id()
    {
        $uid = uniqid("", true);
        $data = $this->namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['SERVER_ADDR'];
        $data .= $_SERVER['SERVER_PORT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
        return substr($hash, 0, 32);
    }
}

//页面执行时间计时
class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;

    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }

    function start()
    {
        $this->StartTime = $this->get_microtime();
    }

    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }

    function spent()
    {
        return round(($this->StopTime - $this->StartTime) * 1000, 1);
    }

}

/**debug print
 * @param $needPrint
 */
function jrPrintDebug($needPrint)
{
    global $CONFIG;
    if (isset($CONFIG['debug']) && $CONFIG['debug']) {
        echo "<pre>";
        print_r($needPrint);
        echo "</pre>";
    }
}


//设置url参数值
function url_set_value($url, $key, $value)
{
    $a = explode('?', $url);
    $url_f = $a[0];
    if (isset($a[1])) {
        $query = $a[1];
        parse_str($query, $arr);
    } else {
        $arr = array();
    }

    $arr[$key] = $value;
    return $url_f . '?' . http_build_query($arr);
}

//根据英文返回星期几
function getWeekDay($weekday)
{
    $temp = "未知";
    switch ($weekday) {
        case 'Friday':
            $temp = "五";
            break;

        case 'Thursday':
            $temp = "四";
            break;

        case 'Wednesday':
            $temp = "三";
            break;

        case 'Tuesday':
            $temp = "二";
            break;

        case 'Monday':
            $temp = "一";
            break;

        case 'Sunday':
            $temp = "日";
            break;

        case 'Saturday':
            $temp = "六";
            break;

        default:
            $temp = "未知";
    }

    return $temp;
}

//时间比较函数，返回两个日期相差几秒、几分钟、几小时或几天
function DateDiff($date1, $date2, $unit = "")
{
    switch ($unit) {
        case 's':
            $dividend = 1;
            break;
        case 'i':
            $dividend = 60;
            break;
        case 'h':
            $dividend = 3600;
            break;
        case 'd':
            $dividend = 86400;
            break;
        default:
            $dividend = 86400;
    }
    $time1 = strtotime($date1);
    $time2 = strtotime($date2);
    if ($time1 && $time2)
        return (float)($time1 - $time2) / $dividend;
    return false;
}

//获取memcached连接
function getMemcachedConnection()
{

    global $CONFIG;
    global $memcachedClient;

    if (!$memcachedClient) {
        $memcachedClient = new Memcached($CONFIG['vendor']);
        //@$memcachedClient->pconnect($CONFIG['CACHE']['HOST'], $CONFIG['CACHE']['PORT']);
        $memcachedClient->setOption(Memcached::OPT_CONNECT_TIMEOUT, 1000); //socket链接超时时间
        $memcachedClient->setOption(Memcached::OPT_RECV_TIMEOUT, 300); // socket读取超时时间
        $memcachedClient->setOption(Memcached::OPT_SEND_TIMEOUT, 300); // socket发送超时时间
        if (count($memcachedClient->getServerList()) == 0) {
            $memcachedClient->addServer($CONFIG['CACHE']['HOST'], $CONFIG['CACHE']['PORT']);
        }

    }

    return $memcachedClient;
}

//获取redis连接
function getRedisConnection()
{
    global $CONFIG;
    global $redisClient;

    if (!$redisClient) {
        $redisClient = new Redis();
        $redisClient->connect($CONFIG['REDIS']['HOST'], $CONFIG['REDIS']['PORT']);
    }
    return $redisClient;
}

//更新缓存信息
function updateMemached($openid, $conn)
{
    global $CONFIG;
    //以下更新缓存
    $sql = "select * from weixin_nickname where fromUsername = '$openid';";
    $query = mysql_query($sql, $conn);
    $row = mysql_fetch_assoc($query);
    if ($row) {
        unset($row['jsonError']);
        //$jsonValue = json_encode_cn($row);
        $final = array_map('urlencode', $row);
        $jsonValue = urldecode(json_encode($final));
        $cache = getMemcachedConnection();
        $key = $CONFIG['CACHE']['PREFIX'] . $openid;
        $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
        //var_dump($ret);
    }
}

//从缓存中获取用户信息
function getWeixinUserInfoFromMemached($openid)
{
    global $CONFIG;

    $cache = getMemcachedConnection();
    $key = $CONFIG['CACHE']['PREFIX'] . $openid;
    return $cache->get($key);
}

//返回结果结构
class FinalResultDefinition
{
    public $rst;
    public $errno;
    public $err;
}

//json格式返回结果
function echoJsonResult($rst, $errno, $errmsg)
{
    $finalResult = compact('rst', 'errno', 'errmsg');
//    $finalResult->rst = $rst;
//    $finalResult->errno = $errno;
//    $finalResult->err = $errmsg;
    echo json_encode_cn($finalResult);
}

//判断是否包含子字符串
function contains($substring, $string)
{
    $pos = strpos($string, $substring);

    if ($pos === false) {
        // string needle NOT found in haystack
        return false;
    } else {
        // string needle found in haystack
        return true;
    }
}

//判断字符串是否是有效json格式
function isValidJson($strJson)
{
    //json_decode($strJson);
    //return (json_last_error() === JSON_ERROR_NONE);
    if ($strJson == '') {
        return false;
    } else {
        return !is_null(json_decode($strJson));
    }
}

//判断字符串是否是有效的时间格式 20140130
function isValidDate($postedDate)
{
    if (ereg("^[0-9]{4}[01][0-9][0-3][0-9]$", $postedDate)) {
        //list($year, $month, $day) = explode('-', $postedDate);
        $year = substr($postedDate, 0, 4);
        $month = substr($postedDate, 4, 2);
        $day = substr($postedDate, 6, 2);
        return (checkdate($month, $day, $year));
    } else {
        return (false);
    }
}

function json_encode_cn($struct)
{
    return preg_replace("/\\\\u([a-f0-9]{4})/e",
        "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

//将数组转换成树结构
function arr2tree($tree, $rootId = 0)
{
    $return = array();
    foreach ($tree as $leaf) {
        if ($leaf['fid'] == $rootId) {
            foreach ($tree as $subleaf) {
                if ($subleaf['fid'] == $leaf['id']) {
                    $leaf['children'] = arr2tree($tree, $leaf['id']);
                    break;
                }
            }
            $return[] = $leaf;
        }
    }
    return $return;
}

//IP地址归化
function ipFilter($key)
{
    $key = preg_replace("/[^0-9.]/", "", $key);
    return preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $key) ? $key :
        "0.0.0.0";
}

//获取客户端ip
function getClientIP()
{
    $ipstr = "";
    if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ipstr .= ipFilter($_SERVER['HTTP_CLIENT_IP']) . ",";
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipstr .= $_SERVER['HTTP_X_FORWARDED_FOR'] . ",";
    }
    if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER'])) {
        $ipstr .= ipFilter($_SERVER['HTTP_PROXY_USER']) . ",";
    }
    if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR'])) {
        $ipstr .= ipFilter($_SERVER['REMOTE_ADDR']) . ",";
    }

    $ip = strtok($ipstr, ",");
    do {
        $ip = trim($ip);
        if (empty($ip)) {
            continue;
        }

        $ip = ip2long($ip);

        //-------------------
        // skip private ip ranges
        //-------------------
        // 10.0.0.0 - 10.255.255.255
        // 172.16.0.0 - 172.31.255.255
        // 192.168.0.0 - 192.168.255.255
        // 127.0.0.1, 255.255.255.255, 0.0.0.0
        //-------------------
        if (!(($ip == 0) or ($ip == (int)0xFFFFFFFF) or ($ip == 0x7F000001) or (($ip >=
                    0x0A000000) and ($ip <= 0x0AFFFFFF)) or (($ip >= (int)0xC0A80000) and ($ip <= (int)
                    0xC0A8FFFF)) or (($ip >= (int)0xAC100000) and ($ip <= (int)0xAC1FFFFF)))
        ) {
            return long2ip($ip);
        }
    } while ($ip = strtok(','));

    //      return "0.0.0.0";
    return ipFilter($_SERVER['REMOTE_ADDR']);
}

//生成uid
function generate_uid($ip)
{
    $output = md5(md5($ip) . md5(time()));
    $rand_str = "" . (mt_rand(0, 10000));
    return substr($output, strlen($rand_str)) . $rand_str;
}

//获取uid
function get_uid()
{
    if (isset($_COOKIE["kmcid"])) {
        $uid = $_COOKIE["kmcid"];
    } else {
        $uid = generate_uid(getClientIP());
        SetCookie("kmcid", $uid, time() + 3600 * 24 * 365 * 20, "/", ".kmsocial.cn");
    }

    return $uid;
}

//获取微信昵称
function getWeixinNickname($conn, $fromUsername)
{
    $result = array();
    $nickname = $fromUsername;
    //先读缓存，再读数据库
    $result = getWeixinUserInfoFromMemached($fromUsername);
    if ($result) {
        $result = json_decode($result, true);
        $nickname = $result['weixinNick'];
    } else {
        $sql = "select * from weixin_nickname where fromUsername='$fromUsername';";
        $query = mysql_query($sql, $conn);
        $row = mysql_fetch_assoc($query);
        if (isset($row['weixinNick'])) {
            $nickname = $row['weixinNick'];
        }
    }


    if ($nickname == "unknown" || $nickname == $fromUsername) {

        if (file_exists('./php/wechat.class.php')) {
            require_once "./php/wechat.class.php";
        } elseif (file_exists('./wechat.class.php')) {
            require_once "./wechat.class.php";
        } elseif (file_exists('../php/wechat.class.php')) {
            require_once "../php/wechat.class.php";
        }
        //调接口
        $wechatObj = new Wechat();
        $wechatObj->setConn($conn);
        $token = $wechatObj->getAccessToken();
        $fansInfo = $wechatObj->getFansInfo($fromUsername, $token, $conn, true);
        if (isset($fansInfo['nickname'])) {
            $nickname = $fansInfo['nickname'];
        }

    }
    return $nickname;
}

//检测微信输入是否合法
function checkSignature($signature, $timestamp, $nonce, $token)
{
    $tmpArr = array(
        $token,
        $timestamp,
        $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);

    if ($tmpStr == $signature) {
        return true;
    } else {
        return false;
    }
}

//连接数据库
function connect_to_db()
{
    global $CONFIG;
    $conn = mysql_connect($CONFIG['ADDB']['HOST'], $CONFIG['ADDB']['USERNAME'], $CONFIG['ADDB']['PASSWORD']);
    mysql_select_db($CONFIG['ADDB']['DATABASE'], $conn);
    $query = "Set Names 'utf8mb4'";
    mysql_query($query, $conn);
    return $conn;
}

//回复文本信息
function responseText($fromUsername, $toUsername, $contentStr)
{
    $time = time();
    $textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
			</xml>";

    return sprintf($textTpl, $fromUsername, $toUsername, $time, $contentStr);

}

//将json格式的图文信息转化为xml格式的图文信息
function jsonNewsToXML($fromUsername, $toUsername, $conn, $responseMessageID, $jsonContent,
                       $isKeyword = false)
{
    global $CONFIG;
    $nickTag = $CONFIG['NickTag'];
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $ua = $_SERVER['HTTP_USER_AGENT'];
        //避免ios用户url中含有中文
        if (contains("iPhone", $ua)) {
            $nickTag = '';
        }
    }
    //咋的都不知道用户终端
    $nickTag = '';
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $content = $jsonContent;
    if ($content != "") {
        $time = time();
        $itemTpl = "<item>
		 							<Title><![CDATA[%s]]></Title> 
		 							<Description><![CDATA[%s]]></Description>
		 							<PicUrl><![CDATA[%s]]></PicUrl>
		 							<Url><![CDATA[%s]]></Url>
		 						</item>";
        $textTpl = "<xml>
		 <ToUserName><![CDATA[%s]]></ToUserName>
		 <FromUserName><![CDATA[%s]]></FromUserName>
		 <CreateTime>%s</CreateTime>
		 <MsgType><![CDATA[news]]></MsgType>
		 <ArticleCount>%s</ArticleCount>
		 <Articles>
		 %s	 
		 </Articles>
		 <FuncFlag>1</FuncFlag>
		 </xml>";

        $articles = '';

        $itemsArray = json_decode($content, true);
        $count = count($itemsArray);
        $id = 1;
        foreach ($itemsArray as $item) {
            $title = $item['title'];
            $description = isset($item['summary']) ? $item['summary'] : "";
            //加上追踪代码
            if (substr($item['coverImg'], 0, 4) == "http") {
                $picUrl = $item['coverImg'];
            } else {
                $picUrl = $CONFIG['UrlPrefix'] . $item['coverImg'] . "?src=" . $fromUsername;
            }
            $link = isset($item['url']) ? $item['url'] : '';
            //关键词图文信息
            if ($isKeyword) {
                if ($link != '') {
                    $url = $link;
                } else {
                    $url = $CONFIG['UrlPrefix'] . "viewNews.php?id=$responseMessageID&type=keyword&index=$id&srcopenid=" . $fromUsername;
                }
            } else //节点图文信息
            {

                if ($link != '') {
                    $url = $link;
                } else {
                    $url = $CONFIG['UrlPrefix'] . "viewNews.php?id=$responseMessageID&type=node&index=$id&srcopenid=" . $fromUsername;
                }
            }
            $articles .= sprintf($itemTpl, $title, $description, $picUrl, $url);
            $id++;
        }

        $final_result['msg'] = sprintf($textTpl, $fromUsername, $toUsername, $time, $count,
            $articles);
        $final_result['type'] = 'news';
    } else {
        $final_result['msg'] = responseText($fromUsername, $toUsername,
            "小编还没编辑好图文内容哦，请联系我们");
    }
    return $final_result;
}

//获取节点的文本返回信息
function getNodeTextResponse($fromUsername, $toUsername, $conn, $responseMessageID)
{
    $response = '';
    $query = "select type, content from weixin_message where messageID = '$responseMessageID' and isValid = 1";
    $result = mysql_query($query, $conn);
    if (is_resource($result)) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (isset($row['type']) && $row['type'] == "text") {
            $response = $row['content'];
        }
    }

    if ($response == '') {
        $response = '小编还没编辑好文本回复内容，请稍候';
    }

    return responseText($fromUsername, $toUsername, $response);
}

//获取节点图文信息回复
function getNodeNewsResponse($fromUsername, $toUsername, $conn, $responseMessageID)
{
    $content = "";
    $type = 'single';
    $count = 1;
    $query = "select type, content from weixin_message where messageID = '$responseMessageID' and isValid = 1";
    $result = mysql_query($query, $conn);
    if (is_resource($result)) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (isset($row['type'])) {
            $type = $row['type'];
            $content = $row['content'];
        }
    }

    return jsonNewsToXML($fromUsername, $toUsername, $conn, $responseMessageID, $content, false);
}


//获取所有节点信息
function getWeixinNodes($conn)
{
    $weixin_nodes = array();
    $result = mysql_query("select id, parentNode, nodeLevel, nodeName, shortName, inputType, responseType, responseMessageID,comment from weixin_node",
        $conn);
    while ($arr = mysql_fetch_assoc($result)) 
    {
        $id = (int)$arr['id'];
        $comment = '';
        if (isset($arr['comment'])) {
            $comment = $arr['comment'];
        }
        $weixin_nodes[$id] = array(
            'id' => (int)$arr['id'],
            'parentNode' => (int)$arr['parentNode'],
            'nodeLevel' => (int)$arr['nodeLevel'],
            'nodeName' => $arr['nodeName'],
            'shortName' => $arr['shortName'],
            'inputType' => $arr['inputType'],
            'responseType' => $arr['responseType'],
            'comment' => $comment,
            'responseMessageID' => $arr['responseMessageID']);
    }

    return $weixin_nodes;
}

//获取子节点
function getWeixinSubNodes($weixin_nodes, $nodeID)
{
    $result_nodes = array();
    foreach ($weixin_nodes as $node) {
        $id = (int)$node['id'];
        if ($nodeID == $node['parentNode']) {
            $result_nodes[] = $node;
        }
    }

    return $result_nodes;
}

//获取节点路径
function getWeixinNodesPath($weixin_nodes, $nodeID)
{
    $result_path = "根节点";
    if ($nodeID != 0) {
        $parentNode = $weixin_nodes[$nodeID]['parentNode'];
        $result_path = $weixin_nodes[$nodeID]['nodeName'];
        while ($parentNode != 0) {
            if ($parentNode != 0) {
                $result_path = $weixin_nodes[$parentNode]['nodeName'] . " => " . $result_path;
            }
            $parentNode = $weixin_nodes[$parentNode]['parentNode'];
        }
        $result_path = "根节点 => " . $result_path;
    }
    return $result_path;
}


//获取当前节点的默认回复内容
function getDefaultResponse($weixin_nodes, $nodeID, $debug = false)
{
    global $CONFIG;
    if ($nodeID == 0) {
        $response = "请输入数字选择您想要查询的内容：\n";
    } else {
        $nodeName = $weixin_nodes[$nodeID]['nodeName'];
        $response = "您正在查询\"$nodeName\"，请输入数字进一步查询：\n";

        if ($weixin_nodes[$nodeID]['comment'] != '') {
            $response = $weixin_nodes[$nodeID]['comment'];
        }
    }

    $leafs = getWeixinSubNodes($weixin_nodes, $nodeID);
    $leafs = array_sort($leafs, 'shortName');

    if (count($leafs) > 0) {
        foreach ($leafs as $leaf) {
            if ($CONFIG['vendor'] == 'abbott') {
                $response .= "【" . $leaf['shortName'] . "】" . $leaf['nodeName'] . "\n";
            } else {
                $response .= $leaf['shortName'] . ". " . $leaf['nodeName'] . "\n";
            }
        }

        if ($leaf['nodeLevel'] > 1) {
            $response = rtrim($response, '\n');
            if ($debug) {
                $response .= "0. 返回上级菜单 \n";
                $response .= "#. 返回主菜单 \n";
            }
        } else {
            $response = rtrim($response, '\n');
        }
        if (isset($nodeName) && $nodeName == "小安素成长计划") {
            $url = $CONFIG['UrlPrefix'] . "trial/xiaoansu/check-winningList.php";
            $response .= "\n迅速点此<a href=\"$url\"> 链接</a> ，看看都有哪些幸运妈妈已经中奖了呢！";
        }
    } else {
        //$responseType = $weixin_nodes[$nodeID]['responseType'];
        $response = "";
    }
    // else {  //这里要注意4S店信息那里
    //	$response = "请回复您的当前位置信息，以便我们为您查询附近的4s店。\n返回上级菜单请输入0";
    //}

    return $response;
}


//根据所在层级及输入的关键词获取对应的回复
function getKeywordResponseByKeyword($fromUsername, $toUsername, $conn, $currentNodeID,
                                     $keyword)
{
    global $CONFIG;
    $final_result = array(
        'msg' => "欢迎使用" . $CONFIG['brand'] . "微信服务，您的输入暂时我们不能识别，请见谅\n",
        'nodeID' => $currentNodeID,
        'matchedKeyword' => "",
        'type' => 'text');
    $keyword = strtoupper($keyword);
    $query = "select ruleID, ruleName, keywords, type, content,updateTime from weixin_keywords where ruleID != 'e2222222222222222222222222222222' and ruleID != '33333333333333333333333333333333' and isValid = 1 order by updateTime desc";
    $result = mysql_query($query, $conn);
    $matched = 0;
    //先把关键词及其对应关系搞定
    $keywordsArrayExactMatched = array();
    $keywordsArray = array();
    while (($arr = mysql_fetch_array($result, MYSQL_ASSOC)) && $matched == 0) {
        $ruleID = $arr['ruleID'];
        $ruleName = $arr['ruleName'];
        $keywords = json_decode($arr['keywords'], true);
        $type = $arr['type'];
        $content = $arr['content'];
        $updateTime = $arr['updateTime'];
        if ($ruleName == "default" && $type == "text") //代表默认回复
        {
            if ($content == "") {
                $final_result['msg'] = '';
            } else {
                $final_result['msg'] = responseText($fromUsername, $toUsername, $content);
            }
            $final_result['matchedKeyword'] = "default";
        } else {
            foreach ($keywords as $temp) {
                $matchType = $temp['matched'];
                $matchKeyword = trim($temp['keyword']);
                $tempArray = array(
                    "keyword" => strtoupper($matchKeyword),
                    "matchType" => $matchType,
                    "type" => $type,
                    "content" => $content,
                    "updateTime" => $updateTime,
                    "ruleID" => $ruleID,
                    "ruleName" => $ruleName);
                if ($matchType == 1) {
                    $keywordsArrayExactMatched[] = $tempArray;
                } else {
                    $keywordsArray[] = $tempArray;
                }
            }
        }
    }

    //全匹配优先
    //$keywordsArray = array_sort($keywordsArray, 'matchType', "desc");
    $keywordsArrayExactMatched = array_sort($keywordsArrayExactMatched, 'updateTime',
        "desc");
    $keywordsArray = array_sort($keywordsArray, 'updateTime', "desc");

    //print_r($keywordsArray);
    $totalKeywordsArray = array_merge($keywordsArrayExactMatched, $keywordsArray);
    foreach ($totalKeywordsArray as $temp) {
        $matchType = $temp['matchType'];
        $matchKeyword = trim($temp['keyword']);
        $type = $temp['type'];
        $content = $temp['content'];
        $ruleID = $temp['ruleID'];
        $ruleName = $temp['ruleName'];
        if ($matchType == 1) //代表全匹配
        {
            if ($keyword == $matchKeyword) //配上了
            {
                $matched = 1;
                $final_result['matchedKeyword'] = $ruleName . "_" . $matchKeyword;
                break;
            }
        } else {
            $c = explode($matchKeyword, $keyword);
            if (count($c) > 1) {
                $matched = 1;
                $final_result['matchedKeyword'] = $ruleName . "_" . $matchKeyword;
                break;
            }
        }
    }

    //如果配上了，则把关键词输出当做输出
    if ($matched == 1) {
        $crd_result = getKeywordResponse($fromUsername, $toUsername, $conn, $ruleID);
        $final_result['msg'] = $crd_result['msg'];
        $final_result['type'] = $crd_result['type'];
    }

    return $final_result;
    //print_r($final_result);
}

//获取关键词规则回复信息
function getKeywordResponse($fromUsername, $toUsername, $conn, $ruleID)
{
    global $CONFIG;
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $content = "";
    $count = 1;
    $query = "select ruleID, ruleName, keywords, type, content from weixin_keywords where ruleID = '$ruleID' and isValid = 1";
    $result = mysql_query($query, $conn);
    if (is_resource($result)) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (isset($row['type'])) {
            $final_result['type'] = $row['type'];
            if ($row['type'] == 'text') {
                if ($CONFIG['vendor'] == 'abbott') {
                    $unixtime = time();
                    $fromUsername = trim($fromUsername, $unixtime);
                    $token = actionProductToken($fromUsername, $unixtime);
                    $url = $CONFIG['abbott_trio_base_url'] . "weixin?openId=$fromUsername&token=$token&action=bind&unixtime=" .
                        $unixtime;
                    $row['content'] = str_replace("{km_abbott_bd_url}", $url, $row['content']);
                    $url = $CONFIG['abbott_trio_base_url'] . "weixin/unbind?openId=$fromUsername&token=$token&unixtime=" .
                        $unixtime;
                    $row['content'] = str_replace("{km_abbott_qxbd_url}", $url, $row['content']);
                }

                $final_result['msg'] = responseText($fromUsername, $toUsername, $row['content']);
            } else {
                $final_result = jsonNewsToXML($fromUsername, $toUsername, $conn, $ruleID, $row['content'], true);
            }
        }
    }

    return $final_result;
}

//计算两经纬度间球面距离
function getdistance($lng1, $lat1, $lng2 = 116.3230864702, $lat2 = 39.9997311288)
    //根据经纬度计算距离,lng经度， lat纬度
{
    //将角度转为狐度
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2; //两纬度之差,纬度<90
    $b = $radLng1 - $radLng2; //两经度之差,经度<180
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin
            ($b / 2), 2))) * 6378.137;
    return $s;
}

//数组排序
function array_sort($arr, $keys, $type = 'asc')
{
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


//获取微信图文信息内容页面
function getNewsHtmlContent($conn, $messageID, $index, $openid, $srcopenid)
{
    global $CONFIG;
    $resultContent = '';
    $content = "";
    $query = "select type, content, date(updateTime) as updateDate from weixin_message where messageID = '$messageID'";
    $result = mysql_query($query, $conn) or die(mysql_errno() . ",:" . mysql_error());
    if (is_resource($result) && mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (isset($row['type'])) {
            $type = $row['type'];
            $content = $row['content'];
            $updateDate = $row['updateDate'];
        }
    }
    if ($content != "") {
        $time = time();
        $itemsArray = json_decode($content, true);
        $id = 1;
        foreach ($itemsArray as $item) {
            $title = $item['title'];
            $description = isset($item['summary']) ? $item['summary'] : "";
            if (substr($item['coverImg'], 0, 4) == "http") {
                $picUrl = $item['coverImg'];
            } else {
                $picUrl = $CONFIG['UrlPrefix'] . $item['coverImg'];
            }
            if (isset($item['contentDisplay']) && ($item['contentDisplay'] == 'false' || $item['contentDisplay'] == '0')) {
                $contentDisplay = false;
            } else {
                $contentDisplay = true;
            }
            if (isset($item['summaryDisplay']) && ($item['summaryDisplay'] == 'false' || $item['summaryDisplay'] == '0')) {
                $summaryDisplay = false;
            } else {
                $summaryDisplay = true;
            }
            if ($id == $index) //要多图文的第几条信息
            {
                //这里添加适当模板
                $header = '<!doctype html>
							<html lang="en">
								<head>
									<meta charset="utf-8" /> 
									<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" />
									<title>' . $title . '</title>
									<link rel="stylesheet" type="text/css" href="./css/weixinMod.css">
								</head>

								<body>
									<div class="container">';
                $resultContent .= $header;
                //标题
                $title1 = "<h2 class=\"img-title\">$title</h2>";
                $resultContent .= "\n" . $title1;
                //日期介绍
                $intro = "<div class=\"intro\">
							<span class=\"date\">$updateDate</span>
							<span class=\"account\">" . $CONFIG['brand'] . "</span>
							</div><div class=\"content\">";
                $resultContent .= "\n" . $intro;
                //封面
                if ($contentDisplay) {
                    $picUrl1 = '<div class="img-box"><img src="' . $picUrl . '" alt="' . $picUrl . '"></div>';
                    $resultContent .= "\n" . $picUrl1;
                }
                $resultContent .= "<div class=\"text-area\">";
                //简介
                if ($summaryDisplay) {
                    $resultContent .= "\n" . '<p>' . $description . '</p>';
                }
                //正文

                $resultContent .= "\n" . $item['content'];
                $footer = '	</div>
		</div>
	</div>';
                $resultContent .= $footer;
                $unixtime = time();
                $key = "hugjmk5AA4giest5weixinTencentCC@#fKM";
                $token = md5($openid . $key . $unixtime);
                $shareUrl = $CONFIG['UrlPrefix'] . "viewNews.php?id=$messageID&type=node&index=$id&srcopenid=" . $openid;
                if ($openid != 'unknown') {
                    $signPackage = getSignPackage($conn);
                }
                $resultContent .= "<script>	
	var customConfig = {
	PKey: '" . $CONFIG['defaultPkey'] . "',
    srcWeixinID: '" . $srcopenid . "',
    visitWeixinID: '" . $openid . "',
	unixtime: '" . $unixtime . "',
	token: '" . $token . "',
	referUrl: top.location.href,
    logUrl: 'http://weixintrack.kmsocial.cn/sharelog_1_2.php', // 日志接口
	shareToFriendData: { // 分享给朋友的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareDesc\":'" . $description . "',
        \"shareTitle\":'" . $title . "'
    },
    shareToTimelineData: { // 分享到朋友圈的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareTitle\":'" . $title . "'
    },
    shareToWeiboData: { // 分享到腾讯微博的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareDesc\":'" . $description . "',
        \"shareTitle\":'" . $title . "'
    }
    
};
</script>";
                if (isset($signPackage)) {
                    $resultContent .= "<script src=\"http://weixintrack.kmsocial.cn/jquery-2.1.1.min.js\"></script>
<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script>
	<script>
	wx.config({
		appId: '" . $signPackage["appId"] . "',
		timestamp: " . $signPackage["timestamp"] . ",
		nonceStr: '" . $signPackage["nonceStr"] . "',
		signature: '" . $signPackage["signature"] . "',
		jsApiList: [
		// 所有要调用的 API 都要加到这个列表中
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'onMenuShareQQ',
				'onMenuShareWeibo'
			]
		});
		</script>
		<script type=\"text/javascript\" src=\"http://weixintrack.kmsocial.cn/share_1_2.js\"></script>";
                }
                $resultContent .= "</body>
</html>\n";
            }
            $id++;
        }
    }

    return $resultContent;
}

//获取微信关键词图文信息内容页面
function getKeywordsHtmlContent($conn, $ruleID, $index, $openid, $srcopenid)
{
    global $CONFIG;
    $resultContent = "";
    $content = "";
    $query = "select type, content, date(updateTime) as updateDate from weixin_keywords where ruleID = '$ruleID'";
    $result = mysql_query($query, $conn);
    if (is_resource($result) && mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (isset($row['type'])) {
            $type = $row['type'];
            $content = $row['content'];
            $updateDate = $row['updateDate'];
        }
    }

    //print_r($content);
    if ($type != "text" && $content != "") {
        $time = time();
        $itemsArray = json_decode($content, true);
        $id = 1;
        foreach ($itemsArray as $item) {
            $title = $item['title'];
            $description = isset($item['summary']) ? $item['summary'] : "";
            if (substr($item['coverImg'], 0, 4) == "http") {
                $picUrl = $item['coverImg'];
            } else {
                $picUrl = $CONFIG['UrlPrefix'] . $item['coverImg'];
            }
            if (isset($item['contentDisplay']) && ($item['contentDisplay'] == 'false' || $item['contentDisplay'] == '0')) {
                $contentDisplay = false;
            } else {
                $contentDisplay = true;
            }
            if (isset($item['summaryDisplay']) && ($item['summaryDisplay'] == 'false' || $item['summaryDisplay'] == '0')) {
                $summaryDisplay = false;
            } else {
                $summaryDisplay = true;
            }
            if ($id == $index) //多图文的某条图文
            {
                //这里添加适当模板
                $header = '<!doctype html>
							<html lang="en">
								<head>
									<meta charset="utf-8" /> 
									<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" />
									<title>' . $title . '</title>
									<link rel="stylesheet" type="text/css" href="./css/weixinMod.css">
								</head>

								<body>
									<div class="container">';
                $resultContent .= $header;
                //标题
                $title1 = "<h2 class=\"img-title\">$title</h2>";
                $resultContent .= "\n" . $title1;
                //日期介绍
                $intro = "<div class=\"intro\">
							<span class=\"date\">$updateDate</span>
							<span class=\"account\">" . $CONFIG['brand'] . "</span>
							</div><div class=\"content\">";
                $resultContent .= "\n" . $intro;
                //封面
                if ($contentDisplay) {
                    $picUrl1 = '<div class="img-box"><img src="' . $picUrl . '" alt="' . $picUrl . '"></div>';
                    $resultContent .= "\n" . $picUrl1;
                }
                $resultContent .= "<div class=\"text-area\">";
                //简介
                if ($summaryDisplay) {
                    $resultContent .= "\n" . '<p>' . $description . '</p>';
                }
                //正文

                $resultContent .= "\n" . $item['content'];
                $footer = '	</div>
		</div>
	</div>';
                $resultContent .= $footer;
                $unixtime = time();
                $key = "hugjmk5AA4giest5weixinTencentCC@#fKM";
                $token = md5($openid . $key . $unixtime);
                $shareUrl = $CONFIG['UrlPrefix'] . "viewNews.php?id=$ruleID&type=keyword&index=$id&srcopenid=" . $openid;
                if ($openid != 'unknown') {
                    $signPackage = getSignPackage($conn);
                }
                $resultContent .= "<script>	
	var customConfig = {
	PKey: '" . $CONFIG['defaultPkey'] . "',
    srcWeixinID: '" . $srcopenid . "',
    visitWeixinID: '" . $openid . "',
	unixtime: '" . $unixtime . "',
	token: '" . $token . "',
	referUrl: top.location.href,
    logUrl: 'http://weixintrack.kmsocial.cn/sharelog_1_2.php', // 日志接口
	shareToFriendData: { // 分享给朋友的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareDesc\":'" . $description . "',
        \"shareTitle\":'" . $title . "'
    },
    shareToTimelineData: { // 分享到朋友圈的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareTitle\":'" . $title . "'
    },
    shareToWeiboData: { // 分享到腾讯微博的数据
        \"shareImgurl\":'" . $picUrl . "',
        \"shareUrl\":'" . $shareUrl . "',
        \"shareDesc\":'" . $description . "',
        \"shareTitle\":'" . $title . "'
    }
    
};
</script>";
                if (isset($signPackage)) {
                    $resultContent .= "<script src=\"http://weixintrack.kmsocial.cn/jquery-2.1.1.min.js\"></script>
<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script>
	<script>
	wx.config({
		appId: '" . $signPackage["appId"] . "',
		timestamp: " . $signPackage["timestamp"] . ",
		nonceStr: '" . $signPackage["nonceStr"] . "',
		signature: '" . $signPackage["signature"] . "',
		jsApiList: [
		// 所有要调用的 API 都要加到这个列表中
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'onMenuShareQQ',
				'onMenuShareWeibo'
			]
		});
		</script>
		<script type=\"text/javascript\" src=\"http://weixintrack.kmsocial.cn/share_1_2.js\"></script>";
                }
                $resultContent .= "</body>
</html>\n";
            }
            $id++;
        }
    }

    return $resultContent;
}

//获取url内容
function fetchUrlContent($url, $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT,
        'Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0');
    $rawResult = @curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_errno > 0) {
        return "Curl Error ($curl_errno): $curl_error\n";
    } else {
        return $rawResult;
    }
}

//产生随机字符串
function random_string($length, $type = "char")
{
    $hash = '';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_';
    if ($type == "number") {
        $chars = '0123456789';
    }

    $max = strlen($chars) - 1;
    mt_srand((double)microtime() * 1000000);

    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }

    return $hash;
}

//判断字符串是否以子字符串开头
function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}

//判断字符串是否以子字符串结尾
function endsWith($haystack, $needle)
{
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}

//判断是否为有效手机号
function isValidPhoneNumber($phone)
{
    return preg_match("/^1[0-9]{2}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}|17[0-9]{1}[0-9]{8}$/",
        $phone);
}

//token生成
function actionProductToken($openId, $unixtime)
{
    $unixtime = (string )$unixtime;
    $key = "adsf7as345-009jmk5AA4kjysd876345n301732nb36%&CC@#fd34";
    $strLen = strlen($openId);
    $str = $openId[$strLen - 1];
    $str .= $openId[$strLen - 5];
    $str .= $openId[$strLen - 9];
    $str .= $openId[$strLen - 3];
    $str .= $openId[$strLen - 2];
    $str .= $key;
    $str .= $openId[$strLen - 7];
    $str .= $openId[$strLen - 10];
    $str .= $openId[$strLen - 8];
    $str .= $openId[$strLen - 12];
    $str .= $unixtime[0];
    $str .= $unixtime[9];
    $str .= $unixtime[3];
    $str .= $unixtime[2];
    $str .= $unixtime[8];
    $str .= $unixtime[7];
    $str .= $unixtime[9];

    return md5($str);
}

function dataPost($post_string, $url)
{ //POST方式提交数据
    $context = array('http' => array(
        'method' => "POST",
        'header' => "Connection: close\r\n Content-Type: application/x-www-form-urlencoded\r\n User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*",
        'content' => $post_string));
    $stream_context = stream_context_create($context);
    $data = file_get_contents($url, false, $stream_context);
    return $data;
}

//获取lbs返回html  大众4S店
function getSVWHtmlContent($conn, $id)
{
    global $CONFIG;
    $resultContent = '';
    $sql = "select id, name, address, postCode, fax, phone, mapUrl,date(updateTime) as updateDate from svw_4s_all where id='$id' and isValid=1";
    $result = mysql_query($sql, $conn);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $fileid = $row['id'];
        $name = $row['name'];
        $encode_name = urlencode($row['name']);
        $address = $row['address'];
        $postCode = $row['postCode'];
        $fax = $row['fax'];
        $phone = $row['phone'];
        $mapUrl = $row['mapUrl'];
        $updateDate = $row['updateDate'];

        //下面生成内容文件
        $title = $name;
        $description = "地址：" . $address;

        if ($phone != '') {
            $description .= "<br>电话：$phone";
        }

        if ($fax != '') {
            $description .= "<br>传真：$fax";
        }

        if ($postCode != '') {
            $description .= "<br>邮编：$postCode";
        }

        //$picUrl = "http://wx.kmsocial.cn/svw/".$mapUrl;
        $picUrl = $mapUrl;
        //$picUrl = "http://api.map.baidu.com/staticimage?width=400&height=400&center=$encode_name&markers=$encode_name&zoom=18&markerStyles=m,A,0xff0000";

        $header = '<html>
		<head>
			<title>查看4S店图文</title>
			<meta charset="utf-8" /> 
			<meta name="viewport" content="width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=1.0" />
			<link rel="stylesheet" type="text/css" href="./css/showPage.css">
			<script type="text/javascript" src="./js/jQuery.js"></script>
		</head>
	
		<body>
			<div id="pageList">
				<div class="page">';
        $resultContent = $header;
        //标题
        $title = "<h1 class=\"title\">$title</h1>";
        $resultContent .= "\n" . $title;
        //日期
        $resultContent .= "\n" . "<date>$updateDate</date>";
        //封面
        $picUrl = '<div class="coverImg"><a href="' . $picUrl . '"><img src="' . $picUrl .
            '"/></a></div>';
        $resultContent .= "\n" . $picUrl;
        //简介
        $resultContent .= "\n" . '<div class="content">' . $description . '</div>';
        //正文
        //$wenzhang = '<div class="content">'.$item['content'].'</div>';
        //fwrite($fp, $wenzhang);
        $footer = '</div>
			</div>
			<script type="text/javascript" src="./js/showPage.js"></script>
		</body>
	
	</html>';
        $resultContent .= "\n" . $footer;
    }
    return $resultContent;
}

//判断是否英文
function isEN($str = '')
{
    $len1 = strlen($str);
    $len2 = mb_strlen($str, 'gbk');
    if ($len1 == $len2)
        return true;
    return false;
}

//上传多媒体文件
function uploadMediaFile($token, $filename, $type, $conn)
{
    $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$token&type=$type";
    //$filepath = dirname(__file__) . "\winter.jpg";
    $filedata = array("file1" => "@" . $filename);
    $result = enhancedUploadMediaFile('', $url, '上传多媒体文件', 'upload_' . $type, $conn,
        $filedata);
    return $result;
}

//获取url内容，除返回结果外，还会往数据库记录信息
function enhancedUploadMediaFile($fromUsername, $url, $module, $type, $conn, $data = null)
{
    $runtime = new runtime;
    $runtime->start();

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);

    $runtime->stop();
    $fetchTime = $runtime->spent();
    $temp = mysql_real_escape_string($result);
    $sql = "insert into api_logs (weixinID, type, url, module, result, fetchTime, updateTime) ";
    $sql .= " values ('$fromUsername', '$type', '$url', '$module', '$temp', $fetchTime, now())";
    mysql_query($sql, $conn);
    return $result;
}

//根据mediaid、token获取多媒体文件
function getMediaFile($token, $mediaID, $filename)
{
    $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$token&media_id=$mediaID";
    $fileInfo = downloadWeixinFile($url);
    saveWeixinFile($filename, $fileInfo["body"]);

    if (file_exists($filename)) {
        return true;
    } else {
        return false;
    }
}

//下载文件
function downloadWeixinFile($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0); //只取body头
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
    return $imageAll;
}

//保存微信文件
function saveWeixinFile($filename, $filecontent)
{
    $local_file = fopen($filename, 'w');
    if (false !== $local_file) {
        if (false !== fwrite($local_file, $filecontent)) {
            fclose($local_file);
        }
    }
}

//获取url内容，除返回结果外，还会往数据库记录信息
function enhancedFetchUrlContent($fromUsername, $url, $module, $type, $conn, $timeout =
2, $changeEncode = true)
{
    $runtime = new runtime;
    $runtime->start();
    //$result = mb_convert_encoding(fetchUrlContent($url, 2), "UTF-8", "gbk");
    if ($changeEncode) {
        $result = iconv("gbk", "UTF-8//IGNORE", fetchUrlContent($url, $timeout));
    } else {
        $result = fetchUrlContent($url, $timeout);
    }
    $runtime->stop();
    $fetchTime = $runtime->spent();
    $temp = mysql_real_escape_string($result);
    $sql = "insert into api_logs (weixinID, type, url, module, result, fetchTime, updateTime) ";
    $sql .= " values ('$fromUsername', '$type', '$url', '$module', '$temp', $fetchTime, now())";
    mysql_query($sql, $conn);
    return $result;
}

function getWeixinAccessToken($conn) //获取access_token
{
    global $CONFIG;
    $appid = $CONFIG['appid'];
    $secret = $CONFIG['secret'];
    $token = "unknown";

    //先看库里有的是否过期
    $result = mysql_query("select * from weixin_token where appID='$appid' and expireTime > now()", $conn);
    if (is_resource($result) && mysql_num_rows($result) != 0) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $token = $row['token'];
    } else {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $data = enhancedFetchUrlContent("unknown", $url, "getToken", "获取token", $conn, 2, false); //通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true); //转为数组

        if (isset($resultArr["access_token"])) {
            $token = $resultArr["access_token"]; //获取access_token
            $expires_in = $resultArr["expires_in"];
            $sql = "insert into weixin_token (appID, secret, token, expireTime, updateTime) ";
            $sql .= "values ('$appid', '$secret', '$token', (now() + interval $expires_in second), now()) ";
            $sql .= " on DUPLICATE KEY UPDATE token='$token', expireTime=(now() + interval $expires_in second), updateTime = now();";
            mysql_query($sql, $conn);
        }
    }
    return $token;
}

function getWeixinOpenid($code) //从oauth接口获得访问当前页面的微信用户openid
{
    global $CONFIG;
    $openid = "unknown";

    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $CONFIG['appid'] .
        "&secret=" . $CONFIG['secret'] . "&code=$code&grant_type=authorization_code";
    $data = fetchUrlContent($url); //通过自定义函数getCurl得到https的内容
    $resultArr = json_decode($data, true); //转为数组

    //print_r($resultArr);
    /*
    {
    "access_token":"ACCESS_TOKEN",
    "expires_in":7200,
    "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",
    "scope":"SCOPE"
    }
    */

    if (isset($resultArr["openid"])) {
        $openid = $resultArr["openid"]; //获取openid
    }

    return $openid;
}

//从oauth接口获得访问当前页面的微信用户账号信息
function getVisitWeixinuserInfo($conn, $code)
{
    global $CONFIG;
    $final_result = array('openid' => "unknown", 'isFans' => 0);

    if ($code != 'authdeny') {


        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $CONFIG['appid'] .
            "&secret=" . $CONFIG['secret'] . "&code=$code&grant_type=authorization_code";
        $data = enhancedFetchUrlContent('unknown', $url, "微信授权", "weixinOauth", $conn);
        //$data = fetchUrlContent($url); //通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true); //转为数组

        //print_r($resultArr);
        /*
        {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE"
        }
        */

        if (isset($resultArr["openid"])) {
            $final_result['openid'] = $resultArr["openid"]; //获取openid
            $openid = $final_result['openid'];
            $final_result['access_token'] = $resultArr["access_token"];

            //如果库里没拿到有效信息，那么考虑通过接口去拿
            if (!isset($final_result['nickname']) && $resultArr['scope'] ==
                'snsapi_userinfo' && $final_result['openid'] != "unknown"
            ) {
                $access_token = $resultArr['access_token'];
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
                $data1 = enhancedFetchUrlContent("$openid", $url, "微信授权",
                    "weixinOauth_getUserinfo", $conn, 2, false);
                $resultArr1 = json_decode($data1, true); //转为数组
                if (isset($resultArr1["openid"])) {
                    $final_result['nickname'] = $resultArr1['nickname'];
                    $final_result['sex'] = $resultArr1['sex'];
                    $final_result['city'] = $resultArr1['city'];
                    $final_result['province'] = $resultArr1['province'];
                    $final_result['country'] = $resultArr1['country'];
                    $final_result['headimgurl'] = $resultArr1['headimgurl'];
                    $final_result['fromAPI'] = 1;
                    $final_result['language'] = $resultArr1['language'];

                    $nickname = mysql_real_escape_string($final_result['nickname']);
                    $sex = $final_result['sex']; // 1男 2女 0未知
                    $language = mysql_real_escape_string($final_result['language']);
                    $city = mysql_real_escape_string($final_result['city']);
                    $country = mysql_real_escape_string($final_result['country']);
                    $province = mysql_real_escape_string($final_result['province']);
                    $headimgurl = mysql_real_escape_string($final_result['headimgurl']);

                    //塞入数据库
                    $sql = "insert into weixin_nickname (fromUsername, weixinNick, subscribe, sex, city, province, country, headimgurl, updateTime) ";
                    $sql .= "values ('$openid', '$nickname', 0, $sex, '$city', '$province', '$country', '$headimgurl', now()) ";
                    $sql .= " ON DUPLICATE KEY UPDATE weixinNick='$nickname', sex=$sex, city='$city', ";
                    $sql .= "province='$province', country='$country', headimgurl='$headimgurl', updateTime=now();";
                    mysql_query("$sql", $conn);

                    //通知腾讯更新
                    if ($CONFIG['vendor'] == 'huggies123') {
                        $sql = "insert into needsRefresh (fromUsername, src, createTime) ";
                        $sql .= "values ('$openid', 'oauth', now()) ";
                        mysql_query("$sql", $conn);
                    }

                    //以下更新缓存
                    updateMemached($openid, $conn);
                }
            } else {

                //根据情况看是否要获取用户进一步信息
                if ($final_result['openid'] != "unknown") {
                    $openid = $final_result['openid'];
                    //先读缓存，再读数据库
                    $result = getWeixinUserInfoFromMemached($openid);
                    if ($result) {
                        $row = json_decode($result, true);
                        $final_result['fromMem'] = 1;
                        $error = json_last_error();
                        if ($error !== JSON_ERROR_NONE) {
                            $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
                            $query = mysql_query($sql, $conn);
                            $row = mysql_fetch_assoc($query);
                            $final_result['memJsonError'] = $error;
                        }
                    } else {
                        //先看数据库信息是否满足要求
                        $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
                        $query = mysql_query($sql, $conn);
                        $row = mysql_fetch_assoc($query);
                        updateMemached($openid, $conn);
                        $final_result['fromDB'] = 1;
                    }

                    if (isset($row['fromUsername'])) {
                        $final_result['isFans'] = $row['subscribe'];
                        if ($row['weixinNick'] != 'unknown' && $row['weixinNick'] != $openid) {
                            $final_result['nickname'] = $row['weixinNick'];
                            $final_result['sex'] = $row['sex'];
                            $final_result['city'] = $row['city'];
                            $final_result['province'] = $row['province'];
                            $final_result['country'] = $row['country'];
                            $final_result['headimgurl'] = $row['headimgurl'];
                            $final_result['firstAddTime'] = $row['firstAddTime'];
                            $final_result['subscribe_time'] = $row['subscribe_time'];
                            $final_result['updateTime'] = $row['updateTime'];
                            $final_result['fromAPI'] = 0;
                        }
                    }
                }
            }
        }
    }


    return $final_result;
}

//从数据库获得微信用户账号信息
function getWeixinUserInfo($conn, $openid)
{
    global $CONFIG;
    $final_result = array('openid' => "$openid", 'isFans' => 0);

    //先读缓存，再读数据库
    $result = getWeixinUserInfoFromMemached($openid);
    if ($result) {

        $row = json_decode($result, true);
        $final_result['fromMem'] = 1;
        $error = json_last_error();
        if ($error !== JSON_ERROR_NONE) {
            $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
            $query = mysql_query($sql, $conn);
            $row = mysql_fetch_assoc($query);
            $final_result['memJsonError'] = $error;
        }
    } else {
        //先看数据库信息是否满足要求
        $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
        $query = mysql_query($sql, $conn);
        $row = mysql_fetch_assoc($query);
        updateMemached($openid, $conn);
        $final_result['fromDB'] = 1;
    }

    if (isset($row['fromUsername'])) {
        $final_result['isFans'] = $row['subscribe'];
        if ($row['weixinNick'] != 'unknown' && $row['weixinNick'] != $openid) {
            $final_result['nickname'] = $row['weixinNick'];
            $final_result['sex'] = $row['sex'];
            $final_result['city'] = $row['city'];
            $final_result['province'] = $row['province'];
            $final_result['country'] = $row['country'];
            $final_result['headimgurl'] = $row['headimgurl'];
            $final_result['firstAddTime'] = $row['firstAddTime'];
            $final_result['subscribe_time'] = $row['subscribe_time'];
            $final_result['updateTime'] = $row['updateTime'];
            $final_result['fromAPI'] = 0;
        } else {
            if (file_exists('./php/wechat.class.php')) {
                require_once "./php/wechat.class.php";
            } elseif (file_exists('./wechat.class.php')) {
                require_once "./wechat.class.php";
            } elseif (file_exists('../php/wechat.class.php')) {
                require_once "../php/wechat.class.php";
            } elseif (file_exists('../../php/wechat.class.php')) {
                require_once "../../php/wechat.class.php";
            }
            //调接口
            $wechatObj = new Wechat();
            $wechatObj->setConn($conn);
            $token = $wechatObj->getAccessToken();
            $fansInfo = $wechatObj->getFansInfo($openid, $token, $conn, true);
            if (isset($fansInfo['nickname'])) {
                $final_result = $fansInfo;
                $final_result['fromAPI'] = 1;
            }
        }
    }


    return $final_result;
}

//判断是否微信粉丝
function isWeixinFans($conn, $openid)
{
    //先读缓存，再读数据库
    $result = getWeixinUserInfoFromMemached($openid);
    if ($result) {
        $row = json_decode($result, true);
        //$final_result['fromMem'] = 1;
        $error = json_last_error();
        if ($error !== JSON_ERROR_NONE) {
            $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
            $query = mysql_query($sql, $conn);
            $row = mysql_fetch_assoc($query);
        }
    } else {
        //先看数据库信息是否满足要求
        $sql = "select * from weixin_nickname where fromUsername = '$openid' limit 1";
        $query = mysql_query($sql, $conn);
        $row = mysql_fetch_assoc($query);
    }

    if (isset($row['subscribe']) && $row['subscribe'] == 1) {
        return true;
    } else {
        return false;
    }
}

function test_news($fromUsername, $toUsername, $conn, $weixin_nodes, $weixinPostObj)
{
    global $CONFIG;
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $fromUsername = trim($fromUsername);

    $itemsArray = array();
    $itemsArray[] = array(
        "title" => "图文列表如下",
        'summary' => '',
        'coverImg' => "",
        'url' => '');
    $itemsArray[] = array(
        "title" => "您的邀请码是：123456",
        'summary' => '',
        'coverImg' => $CONFIG['UrlPrefix'] . "trial_huggies/coupon/img/invite.jpg",
        'url' => 'http://www.kmsocial.cn');
    $itemsArray[] = array(
        "title" => "领取红包",
        'summary' => '',
        'coverImg' => $CONFIG['UrlPrefix'] . "trial_huggies/coupon/img/linghongbao.jpg",
        'url' => 'http://www.kmsocial.cn');
    /*
    $itemsArray[] = array(
    "title" => "邀请排行榜",
    'summary' => '',
    'coverImg' => "images/2de4c86c246341c08f5c19dd78c4febc.jpg",
    'url' => 'trial_huggies/coupon/ranking.php');
    $itemsArray[] = array(
    "title" => "中奖名单",
    'summary' => '',
    'coverImg' => "images/f491c60b2405ed5ef8430b2467b0cab0.jpg",
    'url' => 'trial_huggies/coupon/winList.php');
    */
    $unixtime = time();
    $token = actionProductToken($fromUsername, $unixtime);
    $itemTpl = "<item>
                    <Title><![CDATA[%s]]></Title> 
		 			<Description><![CDATA[%s]]></Description>
		 			<PicUrl><![CDATA[%s]]></PicUrl>
		 			<Url><![CDATA[%s]]></Url>
		 		</item>";
    $textTpl = "<xml>
		 <ToUserName><![CDATA[%s]]></ToUserName>
		 <FromUserName><![CDATA[%s]]></FromUserName>
		 <CreateTime>%s</CreateTime>
		 <MsgType><![CDATA[news]]></MsgType>
		 <ArticleCount>%s</ArticleCount>
		 <Articles>
		 %s	 
		 </Articles>
		 <FuncFlag>1</FuncFlag>
		 </xml>";

    $articles = '';

    $count = count($itemsArray);
    $id = 1;
    foreach ($itemsArray as $item) {
        $title = $item['title'];
        $description = isset($item['summary']) ? $item['summary'] : "";
        //加上追踪代码
        $picUrl = $item['coverImg'];
        $url = $item['url'];
        $articles .= sprintf($itemTpl, $title, $description, $picUrl, $url);
        $id++;
    }

    $final_result['msg'] = sprintf($textTpl, $fromUsername, $toUsername, $unixtime,
        $count, $articles);
    $final_result['type'] = 'news';

    return $final_result;
}

//判断是否为微信浏览器登录
function isWeixinBrowser()
{
    $isWeixinBrowser = 0;
    $useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
    if (strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false) {
        $isWeixinBrowser = 0;
    } else {
        $isWeixinBrowser = 1;
    }
    return $isWeixinBrowser;
}

//更新好奇T5红包数据缓存信息
function updateMemachedHuggiesT5Status($conn, $openid)
{
    global $CONFIG;
    //以下更新缓存
    $sql = "select * from huggies_T5_hongbao_jifen_log where weixinID = '$openid';";
    $query = mysql_query($sql, $conn);
    $row = mysql_fetch_assoc($query);
    if ($row) {
        $final = array_map('urlencode', $row);
        $jsonValue = urldecode(json_encode($final));
        $cache = getMemcachedConnection();
        $key = "huggies_T5_Status_" . $openid;
        $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
        //var_dump($ret);
    }
}

//获取好奇T5红包数据
function getHuggiesT5Status($conn, $openid)
{
    global $CONFIG;
    $final_result = array('weixinID' => "$openid", 'isT5User' => -1);

    $cache = getMemcachedConnection();
    $key = "huggies_T5_Status_" . $openid;
    $result = $cache->get($key);

    if ($result) {
        $row = json_decode($result, true);
        $final_result = $row;
        $final_result['fromMem'] = 1;
        $final_result['isT5User'] = 1;
    } else {
        //再看数据库信息是否满足要求
        $sql = "select * from huggies_T5_hongbao_jifen_log where weixinID = '$openid';";
        $query = mysql_query($sql, $conn);
        $row = mysql_fetch_assoc($query);
        if ($row) {
            $final_result = $row;
            $final_result['fromDB'] = 1;
            $final_result['isT5User'] = 1;
            $jsonValue = urldecode(json_encode($row));
            $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
            //var_dump($ret);
        }
    }

    return $final_result;
}

//删除好奇T5红包数据缓存
function deleteHuggiesT5Status($openid)
{
    global $CONFIG;

    $cache = getMemcachedConnection();
    $key = "huggies_T5_Status_" . $openid;
    $result = $cache->delete($key);

    return true;
}


//调用客服接口进行发送图文
function sendKefuNews($openid, $finalArticles, $token, $conn)
{
    $runtime = new runtime;
    $runtime->start();

    $type = 'news';
    $massArray = array();
    $massArray['touser'] = $openid;
    $massArray['msgtype'] = $type;
    $massArray[$type] = $finalArticles;

    //$postContent = urldecode(json_encode($massArray));
    $postContent = json_encode_cn($massArray);
    $postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
    $result = json_decode(dataPost($postContent, $postUrl), true);

    $runtime->stop();
    $fetchTime = $runtime->spent();
    $temp = mysql_real_escape_string("postContent: " . $postContent . "\nresult: " .
        $result);
    $sql = "insert into api_logs (weixinID, type, url, module, result, fetchTime, updateTime) ";
    $sql .= " values ('$openid', 'sendKefuNews', '$postUrl', '客服接口发送', '$temp', $fetchTime, now())";
    mysql_query($sql, $conn);
    return $result;
}


//调用客服接口进行发送文本
/*
{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}
*/
function sendKefuText($openid, $finalArticles, $token, $conn)
{
    $runtime = new runtime;
    $runtime->start();

    $type = 'text';
    $massArray = array();
    $massArray['touser'] = $openid;
    $massArray['msgtype'] = $type;
    $massArray[$type] = $finalArticles;

    //$postContent = urldecode(json_encode($massArray));
    $postContent = json_encode_cn($massArray);
    $postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
    $result = json_decode(dataPost($postContent, $postUrl), true);

    $runtime->stop();
    $fetchTime = $runtime->spent();
    $temp = mysql_real_escape_string("postContent: " . $postContent . "\nresult: " .
        $result);
    $sql = "insert into api_logs (weixinID, type, url, module, result, fetchTime, updateTime) ";
    $sql .= " values ('$openid', 'sendKefuText', '$postUrl', '客服接口发送', '$temp', $fetchTime, now())";
    mysql_query($sql, $conn);
    return $result;
}


//回复openid
function reply_openid($fromUsername, $toUsername, $conn, $weixin_nodes, $weixinPostObj)
{
    global $CONFIG;
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $fromUsername = trim($fromUsername);
    $tempMsg = "$fromUsername";

    $final_result['msg'] = responseText($fromUsername, $toUsername, $tempMsg);
    return $final_result;
}


//获取微信分享URL
function addWeixinShareParameters($phpfile, $srcopenid = '', $campaignID = '')
{
    global $CONFIG;
    $key = "hugjmk5AB24giest5weixinkongmingCC@#fKM";
    $unixtime = time();
    $token = md5($srcopenid . $key . $campaignID . $unixtime);
    $url = $CONFIG['UrlPrefix'] . $phpfile;
    $url = url_set_value($url, "srcopenid", $srcopenid);
    $url = url_set_value($url, "campaignID", $campaignID);
    $url = url_set_value($url, "token", $token);
    $url = url_set_value($url, "unixtime", $unixtime);
    return $url;
}


//验证分享参数
function checkWeixinShareParameters($srcopenid = '', $campaignID = '', $token, $unixtime)
{
    $key = "hugjmk5AB24giest5weixinkongmingCC@#fKM";
    $checkToken = md5($srcopenid . $key . $campaignID . $unixtime);
    if ($token != $checkToken) {
        $result = false;
    } else {
        $result = true;
    }
    return $result;
}

//判断用户是否是新关注
function isNewFans($conn, $openid, $timeQuantum = 14400)
{
    $result = false;
    $userInfo = getWeixinUserInfo($conn, $openid);
    $timepass = time() - $timeQuantum;
    if ($userInfo['firstAddTime'] != '') {
        $attentionTime = $userInfo['firstAddTime'];
    } else {
        $attentionTime = $userInfo['subscribe_time'];
    }
    if ($userInfo['isFans'] == 1 && $timepass < strtotime($attentionTime)) {
        $result = true;
    }
    return $result;
}

//截取指定长度字符串: width 所需修剪的宽度，中英文配比为二比一
function getSubstr($str, $width, $replaceStr = '*')
{
    $origWidth = mb_strwidth($str, 'utf-8');
    if ($origWidth <= $width) {
        return $str;
    }
    //先取尾部
    $endStr = mb_substr($str, -1, 1, 'utf-8');
    $endWidth = mb_strwidth($endStr, 'utf-8');
    //再取前头的
    $prefixStr = mb_strimwidth($str, 0, $width - $endWidth, $replaceStr, "utf-8");

    return $prefixStr . $endStr;
}

function deleteNodeByParentNode($conn, $parentNode)
{
    $tree = array();
    $sql = "SELECT id,responseMessageID FROM `weixin_node` where parentNode='$parentNode';";
    $result = mysql_query($sql, $conn);
    $rows_num = mysql_num_rows($result);
    if ($rows_num == 0) return;
    $tableNameCopy = "weixin_node_" . date("Ymd", time());
    copytable($conn, "weixin_node", $tableNameCopy);
    $parentNode_str = "";
    while ($row = mysql_fetch_assoc($result)) {
        $tree[] = array('id' => $row['id'], 'responseMessageID' => $row['responseMessageID']);
        $parentNode_str .= "'" . $row['id'] . "',";
    }
    $parentNode_str = trim($parentNode_str, ',');
    while (true) {
        $sql = "select id,responseMessageID from weixin_node where parentNode in ($parentNode_str)";
        $result = mysql_query($sql, $conn);
        $num = mysql_num_rows($result);
        if ($num) {
            $parentNode_str = "";
            while ($row = mysql_fetch_assoc($result)) {
                $currentid = $row['id'];
                $currentresponseMessageID = $row['responseMessageID'];
                $parentNode_str .= "'$currentid',";
                $tree[] = array('id' => $currentid, 'responseMessageID' => $currentresponseMessageID);
            }
            $parentNode_str = trim($parentNode_str, ',');
        } else {
            break;
        }
    }
    foreach ($tree as $val) {
        $sql = "update weixin_message set isValid=0 where messageID='" . $val['responseMessageID'] . "'";
        mysql_query($sql, $conn);
        $sql = "delete from weixin_node where id='" . $val['id'] . "'";
        mysql_query($sql, $conn);
    }
}

//备份数据表
function copytable($conn, $tableName, $tableNameCopy)
{
    if (mysql_num_rows(mysql_query("SHOW TABLES LIKE '$tableName'", $conn)) == 1 && mysql_num_rows(mysql_query("SHOW TABLES LIKE '$tableNameCopy'", $conn)) == 0) {
        $createtable = mysql_query("SHOW CREATE TABLE $tableName", $conn);
        $create = mysql_fetch_assoc($createtable);
        $tabledump = str_replace("CREATE TABLE `$tableName`", "CREATE TABLE `$tableNameCopy`", $create['Create Table']) . ";";
        $rows = mysql_query("SELECT * FROM $tableName", $conn);
        $numfields = mysql_num_fields($rows);
        $numrows = mysql_num_rows($rows);
        if ($numrows > 0) {
            if (mysql_query($tabledump, $conn)) {
                while ($row = mysql_fetch_row($rows)) {
                    $comma = "";
                    $tabledump = "INSERT INTO $tableNameCopy VALUES(";
                    for ($i = 0; $i < $numfields; $i++) {
                        $tabledump .= $comma . "'" . mysql_real_escape_string($row[$i]) . "'";
                        $comma = ",";
                    }
                    $tabledump .= ");";
                    mysql_query($tabledump, $conn);
                }
                return 1;
            } else {
                return 0;
            }
        } else {
            return -2;
        }
    } else {
        return -1;//备份数据表已存在或要备份的表不存在
    }
}

function getUserOpenid($fromUsername, $toUsername)
{
    global $CONFIG;
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $fromUsername = trim($fromUsername);
    $tempMsg = $fromUsername;

    $final_result['msg'] = responseText($fromUsername, $toUsername, $tempMsg);

    return $final_result;
}

function getJsApiTicket($conn)
{
    global $CONFIG;
    $appid = $CONFIG['appid'];
    $secret = $CONFIG['secret'];
    $ticket = "unknown";

    //先看库里有的是否过期
    $result = mysql_query("select * from weixin_jsapi_ticket where appID='$appid' and expireTime > now()", $conn);
    if (is_resource($result) && mysql_num_rows($result) != 0) {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $ticket = $row['ticket'];
    } else {
        $accessToken = getWeixinAccessToken($conn);
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $data = enhancedFetchUrlContent("unknown", $url, "getToken", "获取token", $conn, 2, false); //通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true); //转为数组

        if (isset($resultArr["ticket"])) {
            $ticket = $resultArr["ticket"]; //获取access_token
            $expires_in = $resultArr["expires_in"];
            $sql = "insert into weixin_jsapi_ticket (appID, secret, ticket, expireTime, updateTime) ";
            $sql .= "values ('$appid', '$secret', '$ticket', (now() + interval $expires_in second), now()) ";
            $sql .= " on DUPLICATE KEY UPDATE ticket='$ticket', expireTime=(now() + interval $expires_in second), updateTime = now();";
            mysql_query($sql, $conn);
        }
    }
    return $ticket;
}

//获取jsapi签名
function getSignPackage($conn)
{
    global $CONFIG;
    $jsapiTicket = getJsApiTicket($conn);
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $timestamp = time();
    $nonceStr = createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
        "appId" => $CONFIG['appid'],
        "nonceStr" => $nonceStr,
        "timestamp" => $timestamp,
        "url" => $url,
        "signature" => $signature,
        "rawString" => $string
    );
    return $signPackage;
}

function createNonceStr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

//新建数据表
function createTable($conn, $tableName)
{
    if (mysql_num_rows(mysql_query("SHOW TABLES LIKE '$tableName'", $conn)) == 0) {
        $createMapSql = "CREATE TABLE `$tableName` (
			`id` int(11) NOT NULL AUTO_INCREMENT,
			`fromUsername` varchar(64) NOT NULL,
			`round` int(11) DEFAULT NULL,
			`sendTime` datetime DEFAULT NULL,
			PRIMARY KEY (`id`),
			UNIQUE KEY `i_uniq` (`fromUsername`),
			KEY `i_round` (`round`) USING BTREE
		) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;";
        if (mysql_query($createMapSql, $conn)) {
            return 0;//创建数据库成功
        } else {
            return -2;//创建数据库失败
        }
    } else {
        return -1;//数据表已存在
    }
}

//关注回复
function subscribe_defrepaly($fromUsername, $toUsername, $conn, $weixin_nodes, $weixinPostObj)
{
    global $CONFIG;
    $final_result = array('msg' => "欢迎使用" . $CONFIG['brand'] .
        "微信服务，您的输入暂时我们不能识别，请见谅\n", 'type' => 'text');

    $fromUsername = trim($fromUsername);
    $tempMsg = "为U+正式会员，重磅好礼滚滚来袭！9月14日至9月26日，200辆限量版自行车等你抢！详情请点击下方：“自U+行”";
    //链接数据库
    $cons = mssql_connect('116.213.71.221', 'Marlboro', '!Q@W3e4r5tr');
    mssql_select_db('Marlboro', $cons);
    //query语句
    $query = "select * from WXUsers where OpenID='$fromUsername'";
    $res = mssql_query($query);
    if (is_resource($res) && mssql_num_rows($res) != 0) {
        $rows = mssql_fetch_assoc($res);
        $isLogin = $rows['UserID'];
        if ($isLogin == '' || empty($isLogin)) {
            $tempMsg = $tempMsg;
        } else {
            $tempMsg = "万众期待！9月9日，U+正式开幕！";
        }
    }
    $final_result['msg'] = responseText($fromUsername, $toUsername, $tempMsg);
    return $final_result;
}

/**********⬇福州联通公众号⬇️*************/
function fetchUrlContent_POST($url, $data)
{
    $postdata = http_build_query($data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 1 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;

}

/**
 *获取用户的绑定信息
 * @param $conn
 * @param $openid
 * @return array|mixed
 */
function getBindedMemberInfo($conn, $openid)
{
    //先合并key从缓存中获取用户的绑定信息
    global $CONFIG;
    $cache = getMemcachedConnection();
//    var_dump($cache);
    $key = "fzUnicom_binded" . $openid;
    $result = $cache->get($key);
    $result = null;
    $final_result = array('weixinID' => "$openid", 'isbind' => 0);
    if ($result) {
        $row = json_decode($result, true);
        $final_result = $row;
        $final_result['fromMem'] = 1;//标志位来自于缓存
        $final_result['isbind'] = 1;//标志位已经绑定
    } else {
        //再看数据库信息是否满足要求
        $sql = "select * from member_binded where openid = '$openid';";
        $query = mysql_query($sql, $conn);
        $row = mysql_fetch_assoc($query);
        if ($row) {
            $final_result = $row;
            $final_result['fromDB'] = 1;
            $final_result['isbind'] = 1;
            //已下为更新缓存
            $jsonValue = urldecode(json_encode($row));
            $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
        }
    }
    return $final_result;
}

/**
 * 更新用户绑定缓存信息
 * @param $conn
 * @param $openid
 */
function updateBindedMemberInfo($conn, $openid)
{
    global $CONFIG;
    //已下从数据库中读取数据到缓存
    $cache = getMemcachedConnection();
    $key = "fzUnicom_binded" . $openid;
    //-----//
    $sql = "select * from member_binded where openid = '$openid';";
    $query = mysql_query($sql, $conn);
    $row = mysql_fetch_assoc($query);
    if ($row) {
        $jsonValue = urldecode(json_encode($row));
        $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
    }
}

function getIsLocUnicomBinded($conn, $openid)
{
    $isLocUnicom = 0;
    $bindInfo = getBindedMemberInfo($conn, $openid);
    if (isset($bindInfo['isLocUnicom'])) {
        $isLocUnicom = $bindInfo['isLocUnicom'];
    }
    return $isLocUnicom;
}

function sendwxTplMsg($touser_openid, array $data, $tamplate_id, $redictUrl)
{
    if (file_exists('./php/wechat.class.php')) {
        require_once "./php/wechat.class.php";
    } elseif (file_exists('./wechat.class.php')) {
        require_once "./wechat.class.php";
    } elseif (file_exists('../php/wechat.class.php')) {
        require_once "../php/wechat.class.php";
    } elseif (file_exists('../../php/wechat.class.php')) {
        require_once "../../php/wechat.class.php";
    } elseif (file_exists('../../../php/wechat.class.php')) {
        require_once "../../../php/wechat.class.php";
    }

    $wechart = new Wechat(connect_to_db());
    $wechart->sendTplMsg($touser_openid, $tamplate_id, $data, $redictUrl);
}

/**
 * 获取banner的信息
 * @param $conn
 * @return array
 */
function getBannerListInfo($conn)
{
    //先合并key从缓存中获取用户的绑定信息
    global $CONFIG;
    $cache = getMemcachedConnection();
//    var_dump($cache);
    $key = "fzUnicom_banner";
    $result = $cache->get($key);
    $final_result = array();
//    $result = null;
    if ($result)//先看缓存有没有数据
    {
        $row = json_decode($result, true);
        $final_result['list'] = $row;
        $final_result['fromMem'] = 1;//标志位来自于缓存
    } else //再看数据库信息是否满足要求
    {

        $sql = "select * from fzUnicom_banner_config WHERE inUse = '1' ORDER BY id;";
        $query = mysql_query($sql, $conn);
        $temp = array();
        while ($row = mysql_fetch_assoc($query)) {
            $id = $row['id'];
            $temp[$id] = $row;

        }
        $final_result['list'] = $temp;
        $final_result['fromDB'] = 1;
        //已下为更新缓存
        $jsonValue = json_encode_cn($temp);
        $ret = @$cache->set($key, $jsonValue, time() + $CONFIG['CACHE']['LIFETIME']);
    }
    return $final_result;
}

/**解析出url里面的get请求参数
 * @param $url
 * @return array
 */
function getUrlQuery($url)
{
    $info = parse_url($url);
    $query = $info['query'];
    $queryParts = explode('&', $query);


    $params = array();

    foreach ($queryParts as $param) {

        $item = explode('=', $param);

        $params[$item[0]] = $item[1];

    }
    return $params;
}


function OUT_LINK($url, $uid,$page_name)
{
    $url = urlencode($url);
    $uid = urlencode($uid);
    $page = urlencode($page_name);
    $context_url = "http://unicom.lovemojito.com/fzUnicom/api/redirectOutUrl.php?url=$url&uid=$uid&page=$page";
    return $context_url;
}

function jumpToUseWxScanTipPage() {
    $request_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    header("Location:http://didao.lovemojito.com/api/useWxScan.php?j=".urlencode($request_url));
    exit();
}

?>
